
$(function () {
  var audioElement = null
  $('.loading').hide()

  $('.keywords').on('keydown', function (event) {
    if(event.keyCode === 13) {
      $('.submit-song-keywords').trigger('click')
    }
  })

  $('.submit-song-keywords').on('click', function () {
    if(!$('.keywords').val()) {
      alert('关键词不能为空')
    } else {
      searchSong($('.keywords').val())
    }
  })

  const classArr = [
    'list-group-item-success',
    'list-group-item-primary',
    'list-group-item-danger',
    'list-group-item-warning',
    'list-group-item-info',
  ]

  function searchSong(word) {
    $('.loading').show()
    $.ajax({
      type: 'GET',
      url: `http://musicapi.leanapp.cn/search?keywords=${word}`,
      success(res) {
        const songList = res.result.songs

        songList.length === 0 ? $('.empty').show() : $('.empty').hide()

        $('.list-group, .player__album').empty()
        // $('.player__album').empty()
        $.each(songList, function (index, song) {
          $(`<li data-index="${index}" data-id="${song.id}" class="list-group-item ${classArr[(index % 5)]}">
          ${song.name}
          </li>`)
            .appendTo('.list-group')

          $(`<div class="player__albumImg ${index === 0 ? 'active-song' : ''}"
           data-author="${song.name}"
           data-song="NetEasy"
           data-src="${song.id}"
           style="background-image: url(${song.album.artist.img1v1Url})"></div>`)
            .appendTo('.player__album')
          // $(`<li data-id="${song.id}">${song.name}</li>`).appendTo('.container')
        })

        audioElement = document.createElement('audio');
        audioElement.id = 'audio'
        document.body.append(audioElement)
        audioElement.setAttribute('src', `https://music.163.com/song/media/outer/url?id=${$('.active-song').attr('data-src')}.mp3`);
        console.log(audioElement)
        var playhead = document.getElementById("playhead");
        audioElement.addEventListener("timeupdate", function () {
          var duration = this.duration;
          var currentTime = this.currentTime;
          var percentage = (currentTime / duration) * 100;
          playhead.style.width = percentage * 4 + 'px';
        });
        updateInfo();

        $('.loading').hide()
      },
      error(e) {
        console.log(e)
      }
    })
  }

  // console.log($('.container li'))

  $('.list-group').on('click', 'li',function () {
    // document.querySelector('.mp3').pause()
    // $('.mp3').attr('src', `https://music.163.com/song/media/outer/url?id=${id}.mp3`)
    // document.querySelector('.mp3').play()

    const id = $(this).data('id')
    const index = $(this).data('index')

    $('.player__album .player__albumImg')
      .eq(index).addClass('active-song')
      .siblings().removeClass('active-song')

    updateInfo();
    // audioElement.setAttribute('src', $('.active-song').attr('data-src'));
    audioElement.setAttribute('src', `https://music.163.com/song/media/outer/url?id=${$('.active-song').attr('data-src')}.mp3`);
    console.log(audioElement)
    audioElement.play();

    $('.player__play').trigger('click')
  })

  $('.empty').on('click', function () {

    // $('.player__play').trigger('click')
  })


  // var
  // console.log(audioElement)
  var tl = new TimelineMax();
  tl.to('.player__albumImg', 3, {
    rotation: '360deg',
    repeat: -1,
    ease: Power0.easeNone
  }, '-=0.2');
  tl.pause();

  $('.player__play').click(function () {
    if ($('.player').hasClass('play')) {
      $('.player').removeClass('play');
      audioElement.pause();
      TweenMax.to('.player__albumImg', 0.2, {
        scale: 1,
        ease: Power0.easeNone
      })
      tl.pause();
    } else {
      $('.player').addClass('play');
      audioElement.play();
      TweenMax.to('.player__albumImg', 0.2, {
        scale: 1.1,
        ease: Power0.easeNone
      })
      tl.resume();
    }
  });

  function updateInfo() {
    $('.player__author').text($('.active-song').attr('data-author'));
    $('.player__song').text($('.active-song').attr('data-song'));
  }


  // 下一首
  $('.player__next').click(function () {
    if ($('.player .player__albumImg.active-song').is(':last-child')) {
      $('.player__albumImg.active-song').removeClass('active-song');
      $('.player .player__albumImg:first-child').addClass('active-song');
      audioElement.addEventListener("timeupdate", function () {
        var duration = this.duration;
        var currentTime = this.currentTime;
        var percentage = (currentTime / duration) * 100;
        playhead.style.width = percentage * 4 + 'px';
      });
    } else {
      $('.player__albumImg.active-song').removeClass('active-song').next().addClass('active-song');
      audioElement.addEventListener("timeupdate", function () {
        var duration = this.duration;
        var currentTime = this.currentTime;
        var percentage = (currentTime / duration) * 100;
        playhead.style.width = percentage + '%';
      });
    }
    updateInfo();
    // audioElement.setAttribute('src', $('.active-song').attr('data-src'));
    audioElement.setAttribute('src', `https://music.163.com/song/media/outer/url?id=${$('.active-song').attr('data-src')}.mp3`);
    console.log(audioElement)
    audioElement.play();
  });

  // 上一首
  $('.player__prev').click(function () {
    if ($('.player .player__albumImg.active-song').is(':first-child')) {
      $('.player__albumImg.active-song').removeClass('active-song');
      $('.player .player__albumImg:last-child').addClass('active-song');
      audioElement.addEventListener("timeupdate", function () {
        var duration = this.duration;
        var currentTime = this.currentTime;
        var percentage = (currentTime / duration) * 100;
        playhead.style.width = percentage * 4 + 'px';
      });
    } else {
      $('.player__albumImg.active-song').removeClass('active-song').prev().addClass('active-song');
      audioElement.addEventListener("timeupdate", function () {
        var duration = this.duration;
        var currentTime = this.currentTime;
        var percentage = (currentTime / duration) * 100;
        playhead.style.width = percentage + 'px';
      });
    }
    updateInfo();
    // audioElement.setAttribute('src', $('.active-song').attr('data-src'));
    audioElement.setAttribute('src', `https://music.163.com/song/media/outer/url?id=${$('.active-song').attr('data-src')}.mp3`);
    console.log(audioElement)
    audioElement.play();
  });
})

